package com.yugu.park.wx;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yugu.util.StringUtils;
import com.yugu.park.dto.WeChatUserInfo;
import com.yugu.park.exception.BizException;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

/**
 * 微信请求
 * 
 * @author 31631
 *
 */
@Component
public class WxRequest {
	@Value("${wx.miniapp.appid}")
	private String appId;
	@Value("${wx.miniapp.secret}")
	private String appsecret;
	@Resource
	private RestTemplate restTemplate;

	/**
	 * 获取登陆信息和手机号
	 * 
	 * @param code                手机号对应code
	 * @param loginCode登陆信息对应code
	 * @return
	 */
	public WeChatUserInfo getUserPhone(String code, String loginCode) {
		// 小程序登录参数Get请求
		String openidParams = "appid=" + appId + "&secret=" + appsecret + "&js_code=" + loginCode + "&grant_type="
				+ "authorization_code";
		String openidUrl = "https://api.weixin.qq.com/sns/jscode2session?" + openidParams;
		String openIdResult = restTemplate.getForObject(openidUrl, String.class);
		JSONObject openIdJson = JSONObject.parseObject(openIdResult);
		String openid = (String) openIdJson.get("openid");
		String phoneNumber = "";
		if (StringUtils.isNotEmpty(code)) {
			HttpResponse response = HttpRequest
					.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId
							+ "&secret=" + appsecret + "")
					.execute();
			JSONObject tokenJson = JSON.parseObject(response.body());
			String accessToken = tokenJson.get("access_token").toString();
			if (!tokenJson.containsKey("access_token")) {
				throw new BizException("微信官方修改了获取access_token令牌接口！");
			}
			JSONObject jsonCode = new JSONObject();
			jsonCode.put("code", code);
			String resPhone = HttpUtil.post(
					"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken,
					jsonCode.toString());
			if (StringUtils.isEmpty(resPhone) || !resPhone.contains("phone_info")
					|| !resPhone.contains("phoneNumber")) {
				throw new BizException("微信官方修改了小程序获取用户手机号码相关接口！");
			}
			JSONObject resPhoneInfo = JSON.parseObject(resPhone);
			JSONObject phoneInfo = resPhoneInfo.getJSONObject("phone_info");
			phoneNumber = phoneInfo.get("phoneNumber").toString();
		}

		return WeChatUserInfo.builder().openid(openid).phoneNumber(phoneNumber).build();

	}

	public WeChatUserInfo getUser(String code) {
		String openidParams = "appid=" + appId + "&secret=" + appsecret + "&js_code=" + code + "&grant_type="
				+ "authorization_code";
		String openidUrl = "https://api.weixin.qq.com/sns/jscode2session?" + openidParams;
		String openIdResult = restTemplate.getForObject(openidUrl, String.class);
		JSONObject openIdJson = JSONObject.parseObject(openIdResult);
		String openid =(String) openIdJson.get("openid");
		return WeChatUserInfo.builder().openid(openid)
                .build();

	}

}
